﻿using System;
using TMPro;
using UnityEngine;

[Serializable]
public class NoEmojiValidator : TMP_InputValidator
{
    private TMP_InputField InputField { get; set; }

    private int m_startSelectIndex = 0;
    private int m_endSelectIndex = 0;

    private bool IsSelected { get { return m_startSelectIndex != m_endSelectIndex; } }

    public void Init(TMP_InputField inputField)
    {
        InputField = inputField;
        InputField.onTextSelection.AddListener(OnTextSelection);
        InputField.onEndTextSelection.AddListener(OnEndTextSelection);
    }

    private void OnDestroy()
    {
        InputField.onTextSelection.RemoveListener(OnTextSelection);
        InputField.onEndTextSelection.RemoveListener(OnEndTextSelection);
    }

    private void OnTextSelection(string text, int startSelectionIndex, int endSelectionIndex)
    {
        m_startSelectIndex = startSelectionIndex;
        m_endSelectIndex = endSelectionIndex;
    }

    private void OnEndTextSelection(string s, int startSelectionIndex, int endSelectionIndex)
    {
        m_startSelectIndex = startSelectionIndex;
        m_endSelectIndex = endSelectionIndex;
    }

    public override char Validate(ref string text, ref int pos, char ch)
    {
        if ((int)ch >= 55357)
        {
            return '\0';
        }
#if UNITY_EDITOR || UNITY_STANDALONE || UNITY_WEBGL
        if (IsSelected)
        {
            int minIndex = Mathf.Min(m_startSelectIndex, m_endSelectIndex);
            int maxIndex = Mathf.Max(m_startSelectIndex, m_endSelectIndex);
            int length = maxIndex - minIndex;

            text = text.Remove(minIndex, length);
            text = text.Insert(minIndex, ch.ToString());
        }
        else
        {
            text = text.Insert(pos, ch.ToString());
        }
#endif
        pos += 1;
        return ch;
    }
}

